package util.xml;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Builder {
	public static class Attr {
		private String name;
		private String value;

		public Attr(String name, String value) {
			this.name = name;
			this.value = value;
		}
		public String toString() {
			return " " + name + "='" + value + "'";
		}
	}
	private PrintWriter os;
	private ArrayList<String> elemStack = new ArrayList<String>();

	public Builder(PrintWriter os) {
		this.os = os;
	}
	public Builder begin(String name, Attr... attrs) {
		elemStack.add(name);
		os.printf("<%s%s>%n", name, toString(attrs));
		return this;
	}
	public Builder end() {
		os.printf("</%s>%n", elemStack.remove(elemStack.size()-1));
		return this;
	}
	private static String toString(Attr[] attrs) {
		StringBuilder sb = new StringBuilder();
		for (Attr attr : attrs) {
			sb.append(attr);
		}
		return sb.toString();
	}
	public static void main(String[] args) {
		PrintWriter os = new PrintWriter(new OutputStreamWriter(System.out));
		Builder b = new Builder(os);
		b.begin("html");
		b.begin("head");
		b.write("title","Table Content");
		b.end();
		b.begin("body");
		b.begin("table", new Attr("border","1"));
		String[][] tab = 
		{
				{"koko", "KOKO" },
				{"pepe", "PEPE" },
				{"sisi", "SISI" },
		};
		for (String[] row : tab) {
			b.begin("tr");
			for (String s : row) {
				b.write("td", s);
			}
			b.end();
		}
		b.end().end().end();
		os.flush();
	}
	public Builder write(String string) {
		os.write(string);
		return this;
	}
	public Builder write(String name, String content, Attr... attrs) {
		if (content == null) {
			os.printf("<%s%s/>%n", name, toString(attrs));
		} else {
			os.printf("<%s%s>%s</%s>%n", name, toString(attrs), content, name);
		}
		return this;
	}
	public Builder flush() {
		os.flush();
		return this;
	}
}
